<template>
  <NavbarComponent />
  <div class="buy-container">
    <!-- 收货地址模块 -->
    <div class="module-container">
      <h2 class="section-title">   <i class="icon">📍</i>选择收货地址</h2>
      <div class="address-list">
        <div 
          v-for="address in displayedAddresses" 
          :key="address.addressId"
          class="address-card"
          :class="{ 'selected': selectedAddressId === address.addressId }"
          @click="selectAddress(address.addressId)"
        >
          <div class="address-header">
            <span class="receiver">{{ address.receivename }}</span>
            <span class="phone">{{ address.receivephone }}</span>
            <span v-if="address.isDefault" class="default-tag">默认</span>
          </div>
          <div class="address-detail">
            {{ address.province }}{{ address.city }}{{ address.district }}{{ address.street }}{{ address.detail }}
          </div>
        </div>

        <div 
          v-if="showMoreVisible"
          class="show-more"
          @click="toggleShowMore"
        >
          {{ showAllAddresses ? '收起' : '展示更多地址' }}
        </div>
      </div>
    </div>

    <!-- 确认订单模块 -->
    <div class="module-container">
      <h2 class="section-title"><i class="icon">📦</i>确认订单信息</h2>
      <div v-if="productLoading" class="loading">
        <i class="fas fa-spinner fa-spin"></i> 加载中...
      </div>
      <div v-else-if="productList.length" class="order-info">
        <div 
          v-for="product in productList" 
          :key="product.productId"
          class="product-item"
        >
          <div class="product-content">
            <img 
              :src="'http://localhost:8092' + product.images" 
              class="product-image" 
              alt="商品图片"
            >
            <div class="product-details">
              <div class="product-header">
                <h3 class="product-name">{{ product.productName }}</h3>
                <p class="product-price">{{ formatPrice(product.price) }}</p>
                <span class="product-quantity" style="font-size: 20px;">× {{ product.quantity  }} 件</span>
              </div>
              <p class="product-description">{{ product.introduction }}</p>
              <div class="product-footer">
                <p class="stock-info">库存 {{ product.count }} 件</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="error-message">
        <i class="fas fa-exclamation-triangle"></i> 商品加载失败
      </div>
    </div>

    <!-- 付款详情模块 -->
    <div class="module-container">
      <h2 class="section-title"><i class="icon">💳</i>付款详情</h2>
      <div class="payment-details">
        <div class="detail-grid">
          <div class="detail-item">
            <span>商品总数</span>
            <span class="value">{{ totalQuantity }} 件</span>
          </div>
          <div class="detail-item highlight">
            <span>商品总价</span>
            <span class="value">{{ formatPrice(totalPrice) }}</span>
          </div>
        </div>

        <div class="payment-methods">
          <div 
            class="method-item"
            :class="{ 'selected': paymentMethod === 'wechat' }"
            @click="paymentMethod = 'wechat'"
          >
            <div class="method-icon">
              <i class="fab fa-weixin"></i>
            </div>
            <div class="method-info">
              <h3>微信支付</h3>
              <p>推荐微信用户使用</p>
            </div>
          </div>
          <div 
            class="method-item"
            :class="{ 'selected': paymentMethod === 'alipay' }"
            @click="paymentMethod = 'alipay'"
          >
            <div class="method-icon">
              <i class="fab fa-alipay"></i>
            </div>
            <div class="method-info">
              <h3>支付宝支付</h3>
              <p>推荐支付宝用户使用</p>
            </div>
          </div>
        </div>

        <div class="total-section">
          <div class="total-row">
            <span>实付款：</span>
            <span class="total-amount">{{ formatPrice(actualPayment) }}</span>
          </div>
          <button class="submit-btn" @click="submitOrder">
            <i class="fas fa-credit-card"></i> 立即支付
          </button>
        </div>
      </div>
    </div>

    <!-- 支付弹窗 -->
    <transition name="fade">
      <div v-if="showPaymentModal" class="payment-modal">
        <div class="modal-content">
          <div class="modal-header">
            <h3><i class="fas fa-lock"></i> 安全支付</h3>
            <button class="close-btn" @click="showPaymentModal = false">
              <i class="fas fa-times"></i>
            </button>
          </div>
          <div class="payment-info">
            <div class="payment-method">
              <div class="method-logo" :class="paymentMethod">
                <i 
                  class="fab"
                  :class="{
                    'fa-weixin': paymentMethod === 'wechat',
                    'fa-alipay': paymentMethod === 'alipay'
                  }"
                ></i>
              </div>
              <h4>{{ paymentMethod === 'wechat' ? '微信支付' : '支付宝支付' }}</h4>
            </div>
            <div class="amount-display">
              {{ formatPrice(actualPayment) }}
            </div>
          </div>
          <div class="modal-actions">
            <button class="confirm-btn" @click="confirmPayment">
              <i class="fas fa-check-circle"></i> 确认支付
            </button>
            <button class="cancel-btn" @click="showPaymentModal = false">
              返回修改
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import NavbarComponent from '@/components/components/NavbarComponent.vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 用户信息
const userId = ref(null)

// 地址相关
const addresses = ref([])
const selectedAddressId = ref(null)
const showAllAddresses = ref(false)

// 商品相关
const productList = ref([])
const productLoading = ref(false)
// const productIds = computed(() => {
//   return route.query.productIds 
//     ? route.query.productIds.split(',')
//     : []
// })

// 支付相关
const discount = ref(10)
const paymentMethod = ref(null)
const showPaymentModal = ref(false)
const currentOrderData = ref(null)

// 计算属性
const displayedAddresses = computed(() => {
  if (!addresses.value.length) return []
  
  const defaultAddr = addresses.value.find(addr => addr.isDefault === 1)
  const others = addresses.value.filter(addr => !addr.isDefault)
  
  const base = defaultAddr ? [defaultAddr, ...others.slice(0, 2)] : addresses.value.slice(0, 3)
  return showAllAddresses.value ? addresses.value : base
})

const showMoreVisible = computed(() => addresses.value.length > 3)

// 商品总价（使用购物车价格计算）
const totalPrice = computed(() => {
  if(route.query.isSingle === '1'){
    return route.query.price;
  }
  return productsData.value.reduce((sum, item) => {
    return sum + (item.price * item.qty)
  }, 0)
})

// 实际支付金额（包含优惠）
const actualPayment = computed(() => {
  return Math.max(0, totalPrice.value - discount.value)
})

const totalQuantity = computed(() => productList.value.length)

// 方法
const formatPrice = (price) => {
  const priceNumber = parseFloat(price || 0)
  return `¥${priceNumber.toFixed(2)}`
}

const selectAddress = (id) => selectedAddressId.value = id
const toggleShowMore = () => showAllAddresses.value = !showAllAddresses.value

// 数据获取
const fetchUserDetails = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) return null
    
    const response = await axios.get('http://localhost:8092/user/getUserDetails', {
      headers: { Authorization: `Bearer ${token}` }
    })
    return response.data.data?.userId
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

const fetchAddresses = async (userId) => {
  try {
    const response = await axios.get('http://localhost:8092/address/list', {
      params: { userId }
    })
    addresses.value = response.data || []
    const defaultAddr = addresses.value.find(addr => addr.isDefault === 1)
    selectedAddressId.value = defaultAddr?.addressId || null
  } catch (error) {
    console.error('获取地址失败:', error)
  }
}

const fetchProductDetails = async () => {
  if (!productIds.value.length) return
  
  try {
    productLoading.value = true
    
    // 根据ID数量选择接口
    const isSingle = productIds.value.length === 1
    const endpoint = isSingle ? 'getDetailBySingleId' : 'getDetail'
    
    // 动态构建请求参数
    const params = isSingle 
      ? { productId: productIds.value[0] }  // 单ID参数名用productId
      : { productIds: productIds.value.join(',') }  // 多ID参数名用productIds
    
    const response = await axios.get(`http://localhost:8092/product/${endpoint}`, {
      params
    })
    
    if (response.data.code === 200) {
      // 合并接口数据和本地参数
      productList.value = response.data.data.map(product => {
        const localData = productsData.value.find(p => p.pid === product.productId)
        return {
          ...product,
          quantity: localData?.qty || 1, 
          unitPrice: localData?.price || product.price,
          cartId: localData?.cartId
        }
      })
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('商品加载失败，错误码：' + error.response?.status)
  } finally {
    productLoading.value = false
  }
}
// 获取购物车ID列表
const cartIds = computed(() => {
  return route.query.cartIds 
    ? route.query.cartIds.split(',').map(Number)
    : []
})
// 订单处理
const generateOrderNumber = () => {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 10000)
  return `ORDER_${timestamp}_${random}`
}
// 解析商品数据
const productsData = computed(() => {
  try {
    return JSON.parse(decodeURIComponent(route.query.products)) || []
  } catch {
    return []
  }
})
// 总金额
const totalAmount = computed(() => parseFloat(route.query.total) || 0)

// 获取商品ID列表（用于请求详情）
const productIds = computed(() => {
  // 根据isSingle参数选择数据源
  if (route.query.isSingle === '1') {
    // 单商品模式：解析URL参数
    const ids = route.query.productIds;
    return ids ? ids.split(',').map(Number) : [];
  } else {
    // 购物车模式：从JSON数据解析
    return productsData.value.length 
      ? productsData.value.map(p => p.pid)
      : [];
  }
});
const submitOrder = async () => {
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  const token = localStorage.getItem('token')
  const userRes = await axios.get('http://localhost:8092/user/getUserDetails', {
    headers: { Authorization: `Bearer ${token}` }
  })
  const userInfo = userRes.data.data

  currentOrderData.value = {
    orderNumber: generateOrderNumber(),
    userId: userId.value,
    totalAmount: actualPayment.value.toFixed(2),
    orderStatus: 1,
    paymentMethod: paymentMethod.value,
    addressId: selectedAddressId.value,
    cartIds: cartIds.value ,
    salesType: parseInt(route.query.salesType),
    items: productList.value.map(product => ({
      productId: product.productId,
      productName: product.productName,
      price: product.price,
      quantity: product.quantity, 
      sellerId: product.userId,
      images: product.images, 
    })),
    //cartIds: productList.value.map(p => p.cartId),
    userInfo: {
      avatar: userInfo.avatar,
      nickname: userInfo.nickname
    }
  }

  showPaymentModal.value = true
}

const confirmPayment = async () => {
  try {
    currentOrderData.value.orderStatus = 2;
    const response = await axios.post('http://localhost:8092/order/create', 
      currentOrderData.value,
      {
        headers: { 
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      }
    )
      console.log("123123123",response.data.data)
    if (response.data.code === 200) {
      ElMessage.success({ message: '支付成功,订单已生成', duration: 2500 })
      // 新增关闭逻辑
      setTimeout(() => {
        // 尝试关闭窗口（适用于支付专用页面）
        if (window.opener) {
          window.close() // 关闭当前窗口
        } else {
          router.push('/orders') // 非弹出窗口则跳转到订单列表
        }
      }, 1500)
    }
     else {
      ElMessage.error(response.data.msg || '支付失败')
    }
    showPaymentModal.value = false
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error(error.response?.data?.msg || '网络错误')
  }
}

onMounted(async () => {
  userId.value = await fetchUserDetails()
  if (userId.value) await fetchAddresses(userId.value)
  await fetchProductDetails()
})
</script>

<style scoped>
/* 全局样式 */
.buy-container {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1.5rem;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.module-container {
  background: #ffffff;
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1a1a1a;
  padding-bottom: 1rem;
  margin-bottom: 1.5rem;
  border-bottom: 2px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* 地址模块 */
.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
}

.address-card {
  padding: 1.25rem;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #fafafa;
}

.address-card.selected {
  border-color: #ff5500;
  background: #fffaf5;
  box-shadow: 0 2px 8px rgba(255, 85, 0, 0.1);
}

.address-card:hover {
  transform: translateY(-2px);
}

.address-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.receiver {
  font-weight: 500;
  color: #333;
}

.phone {
  color: #666;
  font-size: 0.875rem;
}

.default-tag {
  background: #ff5500;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}

.address-detail {
  color: #666;
  font-size: 0.875rem;
  line-height: 1.5;
}

.show-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 1rem;
  color: #ff5500;
  border: 2px dashed #ffe5d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.show-more:hover {
  background: #fffaf5;
}

/* 商品模块 - 修改部分 */
.product-item {
  padding: 1.5rem;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);
  transition: transform 0.2s ease;
  margin-bottom: 1rem;
}

.product-item:last-child {
  margin-bottom: 0;
}

.product-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.product-content {
  display: flex;
  gap: 1.5rem;
  align-items: flex-start;
}

.product-image {
  width: 180px;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-details {
  flex: 1;
  min-width: 0;
}

/* 修改后的价格数量样式 */
.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  margin-bottom: 1rem;
}

.price-container {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.product-price {
  font-size: 1.125rem;
  color: #ff5500;
  font-weight: 600;
  white-space: nowrap;
  line-height: 1.2;
  margin-bottom: 0.25rem; /* 新增下边距 */
}

.product-quantity {
  color: #666;
  font-size: 0.875rem;
  white-space: nowrap;
}

.product-description {
  color: #666;
  font-size: 0.875rem;
  line-height: 1.6;
  margin: 1rem 0;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1.5rem;
}

.stock-info {
  color: #999;
  font-size: 0.875rem;
}

/* 支付模块 */
.detail-grid {
  display: grid;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: #fafafa;
  border-radius: 8px;
}

.detail-item.highlight {
  background: #fffaf5;
}

.value {
  font-weight: 500;
  color: #333;
}

.payment-methods {
  display: grid;
  gap: 1rem;
  margin: 2rem 0;
}

.method-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1.25rem;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.method-item.selected {
  border-color: #ff5500;
  background: #fffaf5;
}

.method-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  background: #fff0e6;
}

.method-icon i {
  font-size: 1.5rem;
  color: #ff5500;
}

.method-info h3 {
  margin: 0;
  font-size: 1rem;
  color: #333;
}

.method-info p {
  margin: 0.25rem 0 0;
  color: #999;
  font-size: 0.875rem;
}

.total-section {
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 2px solid #f0f0f0;
}

.total-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.total-amount {
  font-size: 1.5rem;
  font-weight: 600;
  color: #ff5500;
}

.submit-btn {
  width: 100%;
  padding: 1.25rem;
  background: #ff5500;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.submit-btn:hover {
  opacity: 0.95;
  box-shadow: 0 4px 6px rgba(255, 85, 0, 0.1);
}

/* 支付弹窗 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 16px;
  width: 400px;
  padding: 2rem;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.25rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.close-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 1.25rem;
  cursor: pointer;
  padding: 0.5rem;
}

.payment-info {
  text-align: center;
  margin: 2rem 0;
}

.method-logo {
  width: 80px;
  height: 80px;
  margin: 0 auto;
  background: #fffaf5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  color: #ff5500;
}

.amount-display {
  font-size: 2rem;
  font-weight: 600;
  color: #ff5500;
  margin: 1.5rem 0;
}

.modal-actions {
  display: grid;
  gap: 1rem;
}

.confirm-btn {
  background: #ff5500;
  color: white;
  padding: 1rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
  padding: 1rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }

  .product-content {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: auto;
  }

  .modal-content {
    width: 90%;
  }
}

@media (max-width: 480px) {
  .module-container {
    padding: 1.5rem;
  }

  .method-item {
    padding: 1rem;
  }

  .method-icon {
    width: 40px;
    height: 40px;
  }

  .product-price {
    font-size: 1rem;
  }

  .product-quantity {
    font-size: 0.8rem;
  }
}

/* 加载状态 */
.loading, .error-message {
  padding: 2rem;
  text-align: center;
  color: #666;
  border-radius: 8px;
  background: #fafafa;
}

.loading i {
  margin-right: 0.5rem;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>